const co = require('co')
const fs = require('fs')
const CryptoJS = require('crypto-js')
const AES = require('crypto-js/aes')
const exec = require('child_process').exec
const readlineSync = require('readline-sync')

const Browser = require('./browser')
const User = require('./user')

co(function*() {
    // 注册
    let register = yield User.register()
    // 登陆
    let user = yield User.login(register.email, register.password)
    while (true) {
        if (!user.data.token) {
            break
        }
        let t = Date.now().toString()
        // 生成MAC地址
        let n = [
            (0x52).toString(16),
            (0x54).toString(16),
            (0x00).toString(16),
            Math.floor((Math.random() * 0xff)).toString(16),
            Math.floor((Math.random() * 0xff)).toString(16),
            Math.floor((Math.random() * 0xff)).toString(16)
        ].join(':')
        // 生成设备ID
        let d = CryptoJS.MD5(`${t}_${n}`).toString()
        // 加密设备ID
        let e = JSON.stringify({
            deviceId: d,
            harddiskId: t,
            macAddr: n,
        })
        let r = CryptoJS.enc.Utf8.parse("vS7*de1uz2r%Jyoh")
        let a = CryptoJS.AES.encrypt(e, r, {
            iv: r,
            mode: CryptoJS.mode.CBC,
            padding: CryptoJS.pad.Pkcs7
        }).toString()
        // 临时用户登陆
        let tempLogin = yield Browser.POST(`https://api.enfi.vip/api/temp/login?dvcId=${d}`, {
            'Content-Type': 'application/json',
        }, {
            encrypted: a,
            distributionId: '',
        })
        console.log(tempLogin.json)
        // 合并临时用户流量，要小写的authorization头
        let mergeTempUser = yield Browser.POST(`https://api.enfi.vip/api/mergeTempUser?dvcId=${user.d}`, {
            'Content-Type': 'application/json',
            'authorization': user.data.token,
            'Cookie': user.cookie,
        }, {
            tempToken: tempLogin.json.data.token,
        })
        console.log(mergeTempUser.json)
        if (mergeTempUser.json.message) {
            console.log('done.')
            break
        }
    }
}).catch(function(err) {
    console.log(err)
})